﻿
using System.Text;

namespace CodeToHtml {
    public class CSharpToHtmlFormatter {
        public string Format(string code) {
            StringBuilder sb = new StringBuilder();

            CodeReaderParameters codeReaderParameters = CodeReaderParameters.CreateCSharpParameters();
            CodeReader reader = new CodeReader(code, codeReaderParameters);

            sb.AppendLine("<style>");
            sb.AppendLine("  .codeComment {");
            sb.AppendLine("    color: #008000;");
            sb.AppendLine("  }");
            sb.AppendLine("  .codeKeyword {");
            sb.AppendLine("    color: #0000FF;");
            sb.AppendLine("  }");
            sb.AppendLine("  .codeString {");
            sb.AppendLine("    color: #A31515;");
            sb.AppendLine("  }");
            sb.AppendLine("</style>");

            sb.AppendLine("<pre class='code'>");
            while (!reader.IsEndOfString()) {
                CodeItem codeItem = reader.ReadCodeItem();
                switch (codeItem.Type) {
                    case CodeItemType.Comment:
                        sb.Append(string.Format("<span class='codeComment'>{0}</span>", EscapeHtml(codeItem.String)));
                        break;
                    case CodeItemType.Delimiter:
                        sb.Append(string.Format("{0}", codeItem.String));
                        break;
                    case CodeItemType.Keyword:
                        sb.Append(string.Format("<span class='codeKeyword'>{0}</span>", EscapeHtml(codeItem.String)));
                        break;
                    case CodeItemType.Other:
                        sb.Append(string.Format("{0}", codeItem.String));
                        break;
                    case CodeItemType.String:
                        sb.Append(string.Format("<span class='codeString'>{0}</span>", EscapeHtml(codeItem.String)));
                        break;
                }
            }
            sb.AppendLine("</pre>");

            return sb.ToString();
        }

        private string EscapeHtml(string str) {
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            return str;
        }
    }
}
